package com.fh.lib_base.mvvm.ui

import android.os.Bundle
import com.fh.lib_base.BR
import com.fh.lib_base.R
import com.fh.lib_base.base.AppManager
import com.fh.lib_base.base.BaseActivity
import com.fh.lib_base.databinding.CommonContainerBinding
import com.fh.lib_base.mvvm.viewmodel.CommonViewModel
import com.fh.lib_base.route.RouteCenter
import me.yokeyword.fragmentation.SupportFragment

/**
 * @author Alwyn
 * @Date 2020/10/19
 * @Description Fragment容器 根据路由地址加载根Fragment
 */
class ContainerFmActivity : BaseActivity<CommonContainerBinding, CommonViewModel>() {
    //用于记录按下回退键时间
    private var backPressTime = 0L

    companion object {
        const val FRAGMENT = "fragment"
        const val BUNDLE = "bundle"
    }

    override fun initContentView(): Int {
        return R.layout.common_container
    }

    override fun initVariableId(): Int {
        return BR.viewModel
    }

    override fun useBaseLayout(): Boolean {
        return false
    }

    override fun initData() {
        val fragmentPath: String? = intent.getStringExtra(FRAGMENT)
        if (fragmentPath.isNullOrBlank()) {
            return
        }
        val args: Bundle? = intent.getBundleExtra(BUNDLE)
        val fragment: SupportFragment = RouteCenter.navigate(fragmentPath,args) as SupportFragment
        if (findFragment(fragment::class.java) == null) {
            loadRootFragment(R.id.fl_container, fragment)
        }
    }
    override fun onBackPressedSupport() {
//        super.onBackPressedSupport()
        if (supportFragmentManager.backStackEntryCount > 0) {
            supportFragmentManager.popBackStack()
        } else {
            processBackPressed()
        }
    }
    private fun processBackPressed() {
        val now = System.currentTimeMillis()
        if (now - backPressTime > 2000) {
            showNormalToast(getString(R.string.press_again_to_exit))
            backPressTime = now
        } else {
            AppManager.instance.appExit()
        }
    }
}